import React from "react";
import { FlatList, Image, Keyboard, ScrollView, StyleSheet, Text } from "react-native";
import BasePage from "../BasePage";
import ViewUtils from "../../utils/ViewUtils";
import NavigationBar from "../common/NavigationBar";
import { commonStyles } from "../../configs/commonStyle";
import { inject, observer } from "mobx-react";
import { Button, TextField, TouchableOpacity, View } from "react-native-ui-lib";
import { IconImage } from "../../utils";
import ListSeparator from "../common/ListSeparator";
import ImagePicker from "react-native-image-crop-picker";
import { Icon, MyFastImage } from "../components";
import ToastUtils from "../../utils/ToastUtils";
import Events from "../../utils/events";
import ReasonListDialog from "../common/ReasonListDialog";
import { reasonData } from "../../configs/config";
import { call, checkCameraPermission, checkStorePermission, setClipboardContent } from "../../utils/util";
import PermissionDialog from "../common/PermissionDialog";
import AddImageActionDialog from "../common/AddImageActionDialog";
import { isAndroid } from "../../configs/platform";


/**
 * 订单申诉
 */
@inject("userStore")
@observer
export default class OrderAppeal extends BasePage {
  constructor(props) {
    super(props);
    this.state = {
      content: "",
      dataList: [{ imgPath: "" }],
      size: 0,
      reasonType: 0,
      data:{},
      items:[]
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData();
  }

  loadData = () => {
    const ordNo = this.props.navigation.getParam("xmbzNo", null);
    let params = {
      token: global.token,
      ordNo,
      showLoading: true,
    };
    axios.get(api.detailByXMBZNo, { params })
      .then(res => {
        logger("订单详情", res);
        if (!IsNullOrEmpty(res.result)) {
          this.setState({
            data: res.result.order || {},
            items: res.result.items || [],
          });
        }
      })
      .catch(e => {
        logger("error", e);
      });
  };

  addOrderTimeOut = () => {
    Keyboard.dismiss()
    const orderNo = this.props.navigation.getParam("xmbzNo", null);
    const {reasonType,content,dataList}=this.state;
    const materials=[];
    dataList&&dataList.map(data=>{
      if(!IsNullOrEmpty(data.imgPath))
      {
        materials.push(data.imgPath)
      }
    })
    if (IsNullOrEmpty(content)) {
      ToastUtils.showFailInfo("请填写申诉说明");
      return;
    }
    let params = {
      token: global.token,
      orderNo,
      explain:content,
      reason:reasonData[reasonType],
      materials:materials.join(','),
      showLoading: true,
    };
    axios.get(api.addOrderTimeOut, { params })
      .then(res => {
        logger("订单详情", res);
        ToastUtils.showSuccessInfo("提交成功");
        Events.publish("RefreshTimeOutOrderList");
        this._onBackPress();
      })
      .catch(e => {
        logger("error", e);
        e.msg && ToastUtils.showFailInfo(e.msg);
      });
  };

  //检测相机和存储权限
  checkCameraPermission = async () => {
    let hasPermission = await checkCameraPermission();
    if (!hasPermission) {
      this.permissionDialog.show("请在系统设置中开启存储授权");
      return;
    }
    hasPermission = await checkStorePermission();
    if (!hasPermission) {
      this.permissionDialog.show("请在系统设置中开启相机授权");
      return;
    }
    this.addImageActionDialog.show();
  };

  openPic = async () => {
    ImagePicker.openPicker({
      cropping: isAndroid(),
      forceJpg:true,
      compressImageMaxWidth:720,
    }).then(res => {
      logger("相册图片", res);
      this.addImageActionDialog.dismiss();
      this.uploadImg(res);
    }).catch(e => {
      logger(e);
      if (e.code == "E_PERMISSION_MISSING") {//没有相机权限
        this.permissionDialog.show("请在系统设置中开启存储授权");
      }
    });
  };

  openCamera = () => {
    ImagePicker.openCamera({
      cropping: isAndroid(),
      forceJpg:true,
      compressImageMaxWidth:720,
    }).then(res => {
      logger(res);
      this.addImageActionDialog.dismiss();
      this.uploadImg(res);
    }).catch(e => {
      logger("打开相机", JSON.stringify(e));
      this.addImageActionDialog.dismiss();
      if (e.code == "E_PERMISSION_MISSING") {//没有相机权限
        this.permissionDialog.show("请在系统设置中开启相机授权");
      }
    });
  };

  uploadImg = (image) => {
    const { dataList } = this.state;
    let params = new FormData();
    params.append("file", {
      uri: image.path,
      type: image.mime,
      name: image.path.substring(image.path.lastIndexOf("\/") + 1),
    });

    axios.post(api.uploadPicture, params, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      showLoading: true,
    })
      .then(res => {
        logger("上传成功", res);
        const temp = dataList.filter(img => img.imgPath != "");
        temp.push({ imgPath: res.prefixUrl+res.key });
        const size = temp.length;
        if (size < 9) {
          temp.push({ imgPath: "" });
        }
        logger("更新数据", temp);
        this.setState({ size, dataList: temp });
      })
      .catch(e => e.msg && this.showToast(e.msg));

  };

  deleteImg = (item) => {
    const { dataList, size } = this.state;
    const count = size - 1;
    const temp = dataList.filter(img => img.imgPath != item.imgPath);
    if (count == 2) {
      temp.push({ imgPath: "" });
    }
    this.setState({ size: count, dataList: temp });
  };

  render_item = ({ item, index }) => {
    const { size } = this.state;
    if (IsNullOrEmpty(item.imgPath)) {
      return (
        <TouchableOpacity
          style={{ ...styles.item_no_border, marginLeft: index && size == 1 > 0 ? 15 : 0 }}
          onPress={() => this.addImageActionDialog.show()}
        >
          <Image style={styles.add_icon}
                 source={IconImage.icon_add} />

        </TouchableOpacity>
      );
    } else {
      return (
        <View
          style={styles.item_border}
        >
          <MyFastImage style={styles.img}
                       defaultSource={IconImage.ic_upload_img}
                       source={{ uri: `${item.imgPath}` }} />

          <TouchableOpacity style={{ position: "absolute", right: 0, top: 0 }}
                            onPress={() => this.deleteImg(item)}>
            <Icon type="AntDesign" name={"closecircle"} size={18} color={"#BCBCBC"} />
          </TouchableOpacity>
        </View>
      );
    }
  };


  render() {
    const { content, dataList, reasonType,data,items } = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          backgroundColor={"transparent"}
          title={"订单申诉"} />
        <View style={commonStyles.container}>
          <ScrollView style={commonStyles.scrollStyle}>
            <View style={styles.infoWrap}>
              <View marginH-15 marginV-10>
                <Text style={commonStyles.text_black_13}>申诉原因：</Text>
              </View>
              <TouchableOpacity activeOpacity={1} style={styles.dateWrap} onPress={() => this.reasonListDialog.show(reasonType)}>
                <Text numberOfLines={1} style={{
                  ...commonStyles.text_black,
                  marginRight: 5,
                }}>{reasonData[reasonType]}</Text>
                <Icon type="AntDesign" name="down" size={12} color={"#CCCCCC"} />
              </TouchableOpacity>
              <View marginH-15 marginT-10>
                <Text style={commonStyles.text_black_13}>申诉说明：</Text>
              </View>
              <View style={styles.content}>
                <TextField
                  multiline
                  hideUnderline
                  black333
                  maxLength={300}
                  defaultValue={content}
                  placeholder={"请填写"}
                  text12
                  style={{ minHeight: 80, textAlignVertical: "top", fontSize: 13 }}
                  onChangeText={content => this.setState({ content })}
                  showCharacterCounter={true}
                />
              </View>
              <View marginH-15 marginV-10>
                <Text style={commonStyles.text_black_13}>说明材料：</Text>
              </View>
              <FlatList
                data={dataList}
                showsVerticalScrollIndicator={false}
                keyboardShouldPersistTaps={"always"}
                extraData={this.state}
                numColumns={3}
                style={{ marginHorizontal: 15 }}
                keyExtractor={(item, index) => "menu_" + index}
                renderItem={this.render_item}
                ItemSeparatorComponent={() => <ListSeparator />}
              />
              <View marginH-15 marginV-10>
                <Text style={commonStyles.text_black_13}>订单信息：</Text>
              </View>
            </View>
            <View style={styles.titleWrap}>
              <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(data?.xmbzNo)}>
              <Text style={commonStyles.text_black_14}>单号：{data?.xmbzNo}</Text>
              </TouchableOpacity>
              <Text style={commonStyles.text_black_14}>{data?.delyTime} {data?.delySTime}-{data?.delyETime}</Text>
            </View>
            <View style={styles.contentWrap}>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>状态</Text>
                <Text style={commonStyles.text_blue_13}>{data?.ordStateName}</Text>
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>收货人</Text>
                <Text style={commonStyles.text_black_13}>{data?.cneeName}</Text>
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>分仓</Text>
                <Text style={commonStyles.text_black_13}>{data?.invoiceHeader}</Text>
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>联系电话</Text>
                {
                  data.cneeTel&&!data.cneeTel.includes('*')?
                    <TouchableOpacity onPress={()=>call(data?.cneeTel,data?.ordNo)}>
                      <Text style={commonStyles.text_black_13}>{data?.cneeTel}</Text>
                    </TouchableOpacity>
                    :<Text style={commonStyles.text_black_13}>{data?.cneeTel}</Text>
                }
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>地址</Text>
                <View marginL-10 flex right>
                  <Text style={commonStyles.text_black_13}>{data?.address1}</Text>
                </View>
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>备注</Text>
                <Text style={commonStyles.text_black_13}>{data?.delyNeeds}</Text>
              </View>
              <View style={styles.itemWrap}>
                <Text style={commonStyles.text_gray_13}>渠道</Text>
                <Text style={commonStyles.text_black_13}>{data?.chanName}</Text>
              </View>
              <View style={{ paddingVertical: 6 }}>
                {
                  items && items.map(data => {
                    // logger("订单号", data.isScan == 0 ? data.id : "");
                    return (
                      <View row marginT-5>
                        <Image source={data.isScan == 0 ? IconImage.ic_unchecked : IconImage.ic_checked}
                               style={{ width: 17, height: 17, marginRight: 5 }} />
                        <View flex>
                          <Text
                            style={commonStyles.text_black_13}>{data?.name}（{data?.unit}）(x{data?.num}）</Text>
                        </View>
                      </View>
                    );
                  })
                }
              </View>
            </View>
          </ScrollView>
          <View>
            <Button label={"提交申诉"} style={styles.btn} labelStyle={commonStyles.text_black} onPress={this.addOrderTimeOut} />
          </View>
        </View>
        <ReasonListDialog ref={r=>this.reasonListDialog=r} callBack={(reasonType)=>this.setState({reasonType})}/>
        <PermissionDialog ref={r => this.permissionDialog = r} />
        <AddImageActionDialog
          ref={r => (this.addImageActionDialog = r)}
          openCamera={() => this.openCamera()}
          openPic={() => this.openPic()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  btn: {
    borderRadius: 4,
    margin: 15,
  },
  btnWrap: {
    marginTop: 15,
    marginHorizontal: 15,
  },
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },

  contentWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  },
  content: {
    padding: 10,
    borderRadius: 5,
    backgroundColor: "white",
    marginTop: 10,
    marginBottom: 6,
    marginHorizontal: 15,
    borderWidth: 1,
    borderColor: "#CCCCCC",
  },
  item_no_border: {
    alignItems: "center",
    justifyContent: "center",
    height: 96,
    width: 96,
    backgroundColor: "white",
    borderRadius: 12,
  },
  item_border: {
    alignItems: "center",
    justifyContent: "center",
    height: 96,
    width: 96,
  },
  add_icon: { width: 48, height: 48 },
  img: { width: 87, height: 87 },
  dateWrap: {
    flexDirection: "row",
    alignItems: "center",
    height: 40,
    justifyContent: "space-between",
    borderRadius: 4,
    borderWidth: 1,
    borderColor: "#CCCCCC",
    paddingHorizontal: 10,
    backgroundColor: "white",
    marginHorizontal: 15,
  },
  infoWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    marginTop: 10,
  },

});
